package com.choudou5.solr.analyzer.filter;

import com.choudou5.solr.analyzer.utils.PinyinUtil;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;

import java.io.IOException;


public class PinyinTransformTokenFilter extends TokenFilter {
    private boolean isOutChinese = true;
    private final CharTermAttribute termAtt = (CharTermAttribute)addAttribute(CharTermAttribute.class);
    private int _minTermLenght = 2;
    private char[] curTermBuffer;
    private int curTermLength;
    private boolean outChinese = true;

    public PinyinTransformTokenFilter(TokenStream input)
    {
        this(input, 2);
    }

    public PinyinTransformTokenFilter(TokenStream input, int minTermLenght)
    {
        this(input, minTermLenght, true);
    }

    public PinyinTransformTokenFilter(TokenStream input, int minTermLenght, boolean isOutChinese)
    {
        super(input);
        this._minTermLenght = minTermLenght;
        if (this._minTermLenght < 1) {
            this._minTermLenght = 1;
        }
        this.isOutChinese = isOutChinese;
    }


    public final boolean incrementToken() throws IOException {
        for (;;)
        {
            if (this.curTermBuffer == null)
            {
                if (!this.input.incrementToken()) {
                    return false;
                }
                this.curTermBuffer = ((char[])this.termAtt.buffer().clone());
                this.curTermLength = this.termAtt.length();
            }
            if ((this.isOutChinese) && (this.outChinese))
            {
                this.outChinese = false;
                this.termAtt.copyBuffer(this.curTermBuffer, 0, this.curTermLength);
                return true;
            }
            this.outChinese = true;
            String chinese = this.termAtt.toString();
            if (PinyinUtil.containsChinese(chinese)) {
                this.outChinese = true;
                if (chinese.length() >= this._minTermLenght) {
                    String chineseTerm = PinyinUtil.getPinYin(chinese);
                    this.termAtt.copyBuffer(chineseTerm.toCharArray(), 0, chineseTerm.length());
                    this.curTermBuffer = null;
                    return true;
                }
            }
            this.curTermBuffer = null;
        }
    }

    public void reset() throws IOException {
        super.reset();
    }

}
